<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 向当前client_id发送数据 
        Gateway::sendToClient($client_id, "Hello $client_id\r\n");
        // 向所有人发送
        Gateway::sendToAll("$client_id login\r\n");
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
   public static function onMessage($client_id,$data)
   {
        // 向所有人发送 
       Gateway::sendToAll("$client_id said $data\r\n");
       $message = json_decode($data, true);

       $message_type = $message['type'];
       switch($message_type) {
           case 'init':
               // uid
               $uid = $message['id'];
               // 设置session
               $_SESSION = array(
                   'username' => $message['username'],
                   'avatar'   => $message['avatar'],
                   'id'       => $uid,
                   'sign'     => $message['sign']
               );
               // 将当前链接与uid绑定
               Gateway::bindUid($client_id, $uid);
               // 通知当前客户端初始化
               $init_message = array(
                   'message_type' => 'init',
                   'id'           => $uid,
               );
               Gateway::sendToClient($client_id, json_encode($init_message));
               // 通知所有客户端添加一个好友
               $reg_message = array('message_type'=>'addList', 'data'=>array(
                   'type'     => 'friend',
                   'username' => $message['username'],
                   'avatar'   => $message['avatar'],
                   'id'       => $uid,
                   'sign'     => $message['sign'],
                   'groupid'  => 1
               ));
               Gateway::sendToAll(json_encode($reg_message), null, $client_id);
               // 让当前客户端加入群组101
               Gateway::joinGroup($client_id, 101);
               return;
           case 'chatMessage':
               // 聊天消息
               $type = $message['data']['to']['type'];
               $to_id = $message['data']['to']['id'];
               $uid = $_SESSION['id'];
               $chat_message = array(
                   'message_type' => 'chatMessage',
                   'data' => array(
                       'username' => $_SESSION['username'],
                       'avatar'   => $_SESSION['avatar'],
                       'id'       => $type === 'friend' ? $uid : $to_id,
                       'type'     => $type,
                       'content'  => htmlspecialchars($message['data']['mine']['content']),
                       'timestamp'=> time()*1000,
                   )
               );
               switch ($type) {
                   // 私聊
                   case 'friend':
                       Gateway::isOnline($to_id,$client_id);
                       return Gateway::sendToUid($to_id, json_encode($chat_message));
                   // 群聊
                   case 'group':
                       return Gateway::sendToGroup($to_id, json_encode($chat_message), $client_id);
               }
               return;
           case 'hide':
           case 'online':
               $status_message = array(
                   'message_type' => $message_type,
                   'id'           => $_SESSION['id'],
               );
               $_SESSION['online'] = $message_type;
               Gateway::sendToAll(json_encode($status_message));
               return;
           case 'ping':
               return;
           default:
               echo "unknown message $data\n";
       }
   }



   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id)
   {
       // 向所有人发送 
       GateWay::sendToAll("$client_id logout\r\n");
   }
}
